﻿using CommonTools;
using CommonTools.Controls;
using shop.Bll.cost;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace shop.cost
{
    public partial class ShuadanConfigForm : Form
    {
        private ShuadanConfigBll _bll = new ShuadanConfigBll();

        public ShuadanConfigForm()
        {
            InitializeComponent();
        }

        private async void ShuadanConfigForm_Load(object sender, EventArgs e)
        {
            var list = await _bll.QueryItems();
            this.grid.SetItems(list,
                a => a.id,
                a => a.ShuadanStock);
        }

        private async void btnok_Click(object sender, EventArgs e)
        {
            var list = new List<ShuadanConfig>();
            foreach (DataGridViewRow row in this.grid.Rows)
            {
                if (row.IsNewRow)
                {
                    break;
                }

                list.Add(new ShuadanConfig()
                {
                    id = row.Cells[cl_id.Index].Value.IsNull(0),
                    ShuadanStock = row.Cells[cl_stock.Index].Value.IsNull(),
                });
            }

            var res = await _bll.SaveConfig(list);

            if (res.IsOk)
            {
                var list2 = await _bll.QueryItems();
                this.grid.SetItems(list2,
                    a => a.id,
                    a => a.ShuadanStock);

                MessageTip.ShowOk(this, "保存完成");
            }
            else
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private async void grid_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            var item = e.Row.Tag as ShuadanConfig;
            if (item != null)
            {
                await _bll.DeleteItem(item.id);
            }
        }
    }
}
